package com.zaofan.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.TopicReply;
import com.zaofan.bean.TopicReplyDTO;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.base.DaoSupportImpl;
import com.zaofan.utils.WebUtils;

public class TopicReplyDao extends DaoSupportImpl<TopicReply> {

	public List<TopicReplyDTO> findByTopicIdWithOther(String begin, String end, String topicId, String replyType,
			String type) {
		try {
			String sql = "select topicreply.*,account.nickName as userName,concat('" + UrlConstant.HOST_URL
					+ "',account.photo) as userPhoto,concat('" + UrlConstant.HOST_URL
					+ "',userimage.image) from topicreply " + "left join account on topicreply.userId = account.id "
					+ "left join userimage on userimage.replyId = topicreply.id "
					+ "where userimage.type = 1 and topicreply.replyId = " + topicId;

			if (!WebUtils.isEmpty(replyType)) {
				sql += " and topicreply.replyType = " + replyType;
			}
			if (!WebUtils.isEmpty(type)) {
				sql += " and topicreply.type = " + type;
			}
			sql += " order by topicreply.type desc,addTime desc limit " + begin + "," + end + ";";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			return runner.query(sql, new BeanListHandler<>(TopicReplyDTO.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Long countByTopicIdWithOther(String topicId, String replyType, String type) {
		try {
			String sql = "select count(*) from topicreply " + "where replyId = " + topicId;
			if (!WebUtils.isEmpty(replyType)) {
				sql += " and topicreply.replyType = " + replyType;
			}
			if (!WebUtils.isEmpty(type)) {
				sql += " and topicreply.type = " + type;
			}
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(getDataSource());
			return runner.query(sql, new ScalarHandler<Long>());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0L;
	}

}
